package main

import (
	"fmt"
	"regexp"
	"strings"
)

// label: disk_free{mount={{mount}},instance={{instance}}}
// labelMap:{"mount":"/app","instance":"1.1.1.1"}
func ReplaceLegend(label string, labelMap map[string]string) string {
	//去除空格
	// label = strings.ReplaceAll(label, " ", "")
	reg := regexp.MustCompile(`(?U){{( *\w+ *)}}`)
	// [[{{mount}} mount] [{{instance}} instance]]
	tmpList := reg.FindAllStringSubmatch(label, -1)
	if len(tmpList) == 0 {
		return label
	}
	var v string
	var ok bool
	for _, vList := range tmpList {
		if len(vList) < 2 {
			continue
		} else {
			v, ok = labelMap[strings.TrimSpace(vList[1])]
			if ok {
				label = strings.ReplaceAll(label, vList[0], v)
			} else {
				// continue
				label = strings.ReplaceAll(label, vList[0], "")
			}
		}
	}
	return label
}

func main() {
	label := "disk_free{mount={{mount}},instance={{instance}}}"
	labelMap := map[string]string{"mount": "/app", "instance": "1.1.1.1"}
	fmt.Println(ReplaceLegend(label, labelMap))
}
